package main.Daoimpl;

/**
 * 作者: ALIM-MASTIK
 * 创建实现: 2023/7/15 9:12
 * 项目名称：chat
 * 软件: IntelliJ IDEA
 */
import main.JdbcUtils;
import main.dao.FriendshipDAO;
import main.pojo.Friendship;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FriendshipDAOImpl implements FriendshipDAO {
    private Connection connection= JdbcUtils.getConnection();
    private QueryRunner queryRunner=new QueryRunner();

    public FriendshipDAOImpl(Connection connection) {
        this.connection = connection;
        this.queryRunner = new QueryRunner();
    }
    public FriendshipDAOImpl(){
    }

    @Override
    public Friendship getFriendshipByID(int friendshipID)  {
        String query = "SELECT * FROM friendships WHERE FriendshipID = ?";
        Friendship friendship = null;
        try {
            friendship = queryRunner.query(connection, query, new BeanHandler<>(Friendship.class), friendshipID);
            return friendship;
        } catch (SQLException e) {
            return null;
        }
    }
    @Override
    public List<Friendship> getFriendshipsByUser(int userID)  {
        String query = "SELECT * FROM friendships WHERE UserID = ?";
        List<Friendship> friendships = new ArrayList<>();
        try {
            friendships = queryRunner.query(connection, query, new BeanListHandler<>(Friendship.class), userID);
            return friendships;
        } catch (SQLException e) {
            return null;
        }
    }
    @Override
    public Boolean createFriendship(Friendship friendship)  {
        String query = "INSERT INTO friendships (FriendshipID, UserID, FriendID) VALUES (?, ?, ?)";
        try {
            if (queryRunner.update(connection, query, friendship.getFriendshipID(), friendship.getUserID(), friendship.getFriendID())>0){
                return true;
            }else {
                return false;
            }
        } catch (SQLException e) {
            return false;
        }
    }
    @Override
    public Boolean deleteFriendship(int friendshipID)  {
        String query = "DELETE FROM friendships WHERE FriendshipID = ?";
        try {
            queryRunner.update(connection, query, friendshipID);
            return true;
        } catch (SQLException e) {
            return false;
        }
    }
}
